//
//  DualMediationMAXInterstitialManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/15.
//

#import "DualMediationMAXInterstitialManager.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "DMInterstitialSceneInterceptor.h"
//#import "IMAdStrategy.h"
#import "DMConfigReader.h"
#import "DMThinkingManager.h"
#import "DMCommercialManager.h"
#import <AdjustSdk/AdjustSdk.h>
// Firebase 相关头文件
#if __has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
#import <FirebaseAnalytics/FirebaseAnalytics.h>
#define FIREBASE_AVAILABLE 1
#else
#define FIREBASE_AVAILABLE 0
#endif

// Facebook 相关头文件
#if __has_include(<FBSDKCoreKit/FBSDKCoreKit.h>)
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#define FACEBOOK_AVAILABLE 1
#else
#define FACEBOOK_AVAILABLE 0
#endif

#if __has_include(<AppLovinSDK/AppLovinSDK.h>)
#import <AppLovinSDK/AppLovinSDK.h>
#define APPLOVIN_SDK_AVAILABLE 1
#else
#define APPLOVIN_SDK_AVAILABLE 0
#endif

#if APPLOVIN_SDK_AVAILABLE
@interface DualMediationMAXInterstitialManager()<MAAdDelegate, MAAdRevenueDelegate>
#else
@interface DualMediationMAXInterstitialManager
#endif

@property (nonatomic, assign) BOOL hasShowAd;
#if APPLOVIN_SDK_AVAILABLE
@property (nonatomic, strong) MAInterstitialAd *interstitialAd;
#else
@property (nonatomic, strong) id interstitialAd;
#endif
@property (nonatomic, copy) NSString *currentScene;
@property (nonatomic, assign) BOOL isUserClosed; // 重新声明为可写属性

// 双广告位相关私有属性
#if APPLOVIN_SDK_AVAILABLE
@property (nonatomic, strong) MAInterstitialAd *primaryInterstitialAd;
@property (nonatomic, strong) MAInterstitialAd *secondaryInterstitialAd;
#else
@property (nonatomic, strong) id primaryInterstitialAd;
@property (nonatomic, strong) id secondaryInterstitialAd;
#endif
@property (nonatomic, copy) NSString *currentAdUnitId;

@end

@implementation DualMediationMAXInterstitialManager

static DualMediationMAXInterstitialManager *_interstitial = nil;

+ (instancetype)sharedInterstitialManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _interstitial = [[self alloc] init];
        [_interstitial initializeDualAdSettings];
    });
    return _interstitial;
}

#pragma mark - 双广告位初始化

- (void)initializeDualAdSettings {
    // 检查是否启用双广告位
    self.isDualAdEnabled = [DMCommercialManager isDualAdEnabledForAdType:@"interstitial"];
    
    if (self.isDualAdEnabled) {
        // 获取主备广告位ID
        self.currentPrimaryAdUnitId = [DMConfigReader primaryInterAdUnitIdForMAX];
        self.currentSecondaryAdUnitId = [DMConfigReader secondaryInterAdUnitIdForMAX];
        
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位已启用"];
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 主广告位ID: %@", self.currentPrimaryAdUnitId];
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 备广告位ID: %@", self.currentSecondaryAdUnitId];
        
        // 初始化双广告位状态
        self.isPrimaryAdLoaded = NO;
        self.isSecondaryAdLoaded = NO;
        self.primaryAdECPM = 0.0;
        self.secondaryAdECPM = 0.0;
        
        // 初始化重试机制
        self.maxRetryCount = 3;
        self.retryCount = 0;
        self.totalLoadAttempts = 0;
        self.totalFailureCount = 0;
        self.isRetryPaused = NO;
        [self loadInterstitial];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位未启用，使用单广告位模式"];
        [self loadInterstitial];
    }
}

#pragma mark - 双广告位方法

- (void)loadDualInterstitialAds {
    if (!self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位未启用，回退到单广告位模式"];
        [self loadInterstitialAd];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 开始加载双广告位"];
    
    // 并行加载主广告位和备用广告位
    [self loadPrimaryInterstitialAd];
    [self loadSecondaryInterstitialAd];
}

- (void)loadPrimaryInterstitialAd {
    if (!self.currentPrimaryAdUnitId || [self.currentPrimaryAdUnitId length] == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] 主广告位ID为空，跳过加载"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 开始加载主广告位: %@", self.currentPrimaryAdUnitId];
    
#if APPLOVIN_SDK_AVAILABLE
    self.primaryInterstitialAd = [[MAInterstitialAd alloc] initWithAdUnitIdentifier:self.currentPrimaryAdUnitId];
    self.primaryInterstitialAd.delegate = self;
    self.primaryInterstitialAd.revenueDelegate = self;
    // 埋点：主广告位填充请求
    NSDictionary *fillRequestParams = @{
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": self.currentPrimaryAdUnitId,
        @"w_ad_position": @"primary"
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    
    [self.primaryInterstitialAd loadAd];
#endif
}

- (void)loadSecondaryInterstitialAd {
    if (!self.currentSecondaryAdUnitId || [self.currentSecondaryAdUnitId length] == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] 备广告位ID为空，跳过加载"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 开始加载备广告位: %@", self.currentSecondaryAdUnitId];
    
#if APPLOVIN_SDK_AVAILABLE
    self.secondaryInterstitialAd = [[MAInterstitialAd alloc] initWithAdUnitIdentifier:self.currentSecondaryAdUnitId];
    self.secondaryInterstitialAd.delegate = self;
    self.secondaryInterstitialAd.revenueDelegate = self;
    // 埋点：备广告位填充请求
    NSDictionary *fillRequestParams = @{
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": self.currentSecondaryAdUnitId,
        @"w_ad_position": @"secondary"
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    
    [self.secondaryInterstitialAd loadAd];
#endif
}

- (NSString *)selectOptimalAdUnitId {
    if (!self.isDualAdEnabled) {
        // 单广告位模式，返回配置的广告位ID
        return [[DMConfigReader sharedInstance]interstitialAdConfigs][1].ad_unitID;
    }
    
    // 双广告位模式下的选择逻辑
    BOOL primaryReady = self.isPrimaryAdLoaded && self.primaryInterstitialAd && [self.primaryInterstitialAd isReady];
    BOOL secondaryReady = self.isSecondaryAdLoaded && self.secondaryInterstitialAd && [self.secondaryInterstitialAd isReady];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 广告位状态检查 - 主广告位: %@, 备广告位: %@", 
     primaryReady ? @"就绪" : @"未就绪", secondaryReady ? @"就绪" : @"未就绪"];
    
    if (primaryReady && secondaryReady) {
        // 两个广告位都就绪，选择ECPM更高的
        if (self.primaryAdECPM >= self.secondaryAdECPM) {
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 选择主广告位 (ECPM: %.4f >= %.4f)", 
             self.primaryAdECPM, self.secondaryAdECPM];
            self.currentAdUnitId = self.currentPrimaryAdUnitId;
            self.interstitialAd = self.primaryInterstitialAd;
            return self.currentPrimaryAdUnitId;
        } else {
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 选择备广告位 (ECPM: %.4f > %.4f)", 
             self.secondaryAdECPM, self.primaryAdECPM];
            self.currentAdUnitId = self.currentSecondaryAdUnitId;
            self.interstitialAd = self.secondaryInterstitialAd;
            return self.currentSecondaryAdUnitId;
        }
    } else if (primaryReady) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 选择主广告位 (仅主广告位就绪)"];
        self.currentAdUnitId = self.currentPrimaryAdUnitId;
        self.interstitialAd = self.primaryInterstitialAd;
        return self.currentPrimaryAdUnitId;
    } else if (secondaryReady) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 选择备广告位 (仅备广告位就绪)"];
        self.currentAdUnitId = self.currentSecondaryAdUnitId;
        self.interstitialAd = self.secondaryInterstitialAd;
        return self.currentSecondaryAdUnitId;
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] 没有可用的广告位"];
        return nil;
    }
}

- (void)switchToSecondaryAdIfNeeded {
    if (!self.isDualAdEnabled) {
        return;
    }
    
    // 如果主广告位加载失败且备用广告位已就绪，切换到备用广告位
    if (!self.isPrimaryAdLoaded && self.isSecondaryAdLoaded && 
        self.secondaryInterstitialAd && [self.secondaryInterstitialAd isReady]) {
        
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 主广告位加载失败，切换到备用广告位"];
        
        self.currentAdUnitId = self.currentSecondaryAdUnitId;
        self.interstitialAd = self.secondaryInterstitialAd;
        
        // 如果有待展示请求，立即展示备用广告位
        if (self.hasShowAd && !self.isUserClosed) {
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 检测到待展示请求，使用备用广告位展示"];
            self.hasShowAd = NO;
            [self showInterAd:self.currentScene ?: SCENE_INTER_LEVEL_WIN];
        }
    }
}

#pragma mark - 私有方法

- (UIViewController *)getRootViewController {
    UIViewController *rootVC = nil;
    if (@available(iOS 13.0, *)) {
        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive &&
                [scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *ws = (UIWindowScene *)scene;
                for (UIWindow *w in ws.windows) {
                    if (w.isKeyWindow) { rootVC = w.rootViewController; break; }
                }
            }
            if (rootVC) { break; }
        }
    }
    if (!rootVC) {
        UIWindow *keyWindow = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        keyWindow = [UIApplication sharedApplication].keyWindow;
#pragma clang diagnostic pop
        if (!keyWindow) {
            for (UIWindow *w in [UIApplication sharedApplication].windows) {
                if (w.isKeyWindow) { keyWindow = w; break; }
            }
        }
        if (!keyWindow) {
            keyWindow = [UIApplication sharedApplication].delegate.window;
        }
        rootVC = keyWindow.rootViewController;
    }
    return [self _topFrom:rootVC];
}

- (UIViewController *)_topFrom:(UIViewController *)vc {
    if (vc.presentedViewController) {
        return [self _topFrom:vc.presentedViewController];
    } else if ([vc isKindOfClass:UINavigationController.class]) {
        return [self _topFrom:((UINavigationController*)vc).visibleViewController];
    } else if ([vc isKindOfClass:UITabBarController.class]) {
        return [self _topFrom:((UITabBarController*)vc).selectedViewController];
    }
    return vc;
}

#pragma mark - 公开方法

- (void)setInterstitialDelegate
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 开始设置插屏广告代理"];
    [self loadInterstitial];
}

- (void)showInterstitial
{
    [self showInterAd:SCENE_INTER_LEVEL_WIN];
}

- (void)showInterAd:(NSString *)adScene {
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] ========== 开始展示插屏广告 =========="];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial] 场景: %@", adScene ?: @"unknown"];
    
    self.currentScene = adScene;

#if APPLOVIN_SDK_AVAILABLE
    if (self.isUserClosed) {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] 用户已主动关闭，不展示广告"];
        NSError *error = [NSError errorWithDomain:@"DualMediationMAXInterstitial" code:1001 userInfo:@{NSLocalizedDescriptionKey: @"用户已关闭"}];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
            [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
        }
        return;
    }
    
    UIViewController *viewController = [self getRootViewController];
    if (!viewController) {
        [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] 无法获取根视图控制器"];
        NSError *error = [NSError errorWithDomain:@"DualMediationMAXInterstitial" code:1002 userInfo:@{NSLocalizedDescriptionKey: @"无法获取根视图控制器"}];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
            [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
        }
        return;
    }
    
    // 双广告位模式下选择最优广告位
    if (self.isDualAdEnabled) {
        NSString *selectedAdUnitId = [self selectOptimalAdUnitId];
        if (!selectedAdUnitId) {
            [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] ❌ 双广告位模式下无可用广告位"];
            NSError *error = [NSError errorWithDomain:@"DualMediationMAXInterstitial" code:1003 userInfo:@{NSLocalizedDescriptionKey: @"双广告位模式下无可用广告位"}];
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
                [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
            }
            
            self.hasShowAd = YES;
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 设置 hasShowAd = YES，将在广告加载完成后自动展示"];
            [self loadDualInterstitialAds];
            return;
        }
        
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位模式选择广告位: %@", selectedAdUnitId];
    }
    
    if (self.interstitialAd && [self.interstitialAd isReady]) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] ✅ 插屏广告准备就绪，开始展示"];
        
        // 埋点：展示请求
        NSMutableDictionary *showRequestParams = [@{
            @"w_ad_scene": adScene ?: @"interstitial_show",
            @"w_ad_type": @"interstitial",
            @"w_ad_unit_id": self.interstitialAd.adUnitIdentifier ?: @""
        } mutableCopy];
        
        // 双广告位模式下添加广告位位置信息
        if (self.isDualAdEnabled) {
            if ([self.interstitialAd.adUnitIdentifier isEqualToString:self.currentPrimaryAdUnitId]) {
                showRequestParams[@"w_ad_position"] = @"primary";
                showRequestParams[@"w_ad_revenue"] = @(self.primaryAdECPM);
            } else if ([self.interstitialAd.adUnitIdentifier isEqualToString:self.currentSecondaryAdUnitId]) {
                showRequestParams[@"w_ad_position"] = @"secondary";
                showRequestParams[@"w_ad_revenue"] = @(self.secondaryAdECPM);
            }
        }
        
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_request" properties:showRequestParams];

        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 埋点事件已发送: adRequest & adShow"];

        dispatch_async(dispatch_get_main_queue(), ^{
            [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial] 在主线程展示插屏广告"];
            [self.interstitialAd showAd];
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 调用 showAd 完成"];
        });
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] ❌ 插屏广告未准备就绪"];
        NSError *error = [NSError errorWithDomain:@"DualMediationMAXInterstitial" code:1003 userInfo:@{NSLocalizedDescriptionKey: @"广告未准备就绪"}];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
            [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
        }
        
        self.hasShowAd = YES;
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 设置 hasShowAd = YES，将在广告加载完成后自动展示"];
        
        // 根据双广告位模式选择加载方法
        if (self.isDualAdEnabled) {
            [self loadDualInterstitialAds];
        } else {
            [self loadInterstitialAd];
        }
    }
#else
    [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] AppLovin SDK 不可用"];
    NSError *error = [NSError errorWithDomain:@"DualMediationMAXInterstitial" code:1004 userInfo:@{NSLocalizedDescriptionKey: @"AppLovin SDK 不可用"}];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
    }
#endif
}

- (void)loadInterstitialAd
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 开始加载插屏广告"];
    
#if APPLOVIN_SDK_AVAILABLE
    if (self.isUserClosed) {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] 用户已关闭，跳过加载"];
        return;
    }
    
    // 创建插屏广告实例
    self.interstitialAd = [[MAInterstitialAd alloc] initWithAdUnitIdentifier:[[DMConfigReader sharedInstance]interstitialAdConfigs][1].ad_unitID];
    self.interstitialAd.delegate = self;
    
    // 埋点：填充请求
    NSDictionary *fillRequestParams = @{
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": self.interstitialAd.adUnitIdentifier ?: @""
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    
    [self.interstitialAd loadAd];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 插屏广告开始加载，AdUnit: %@", [[DMConfigReader sharedInstance]interstitialAdConfigs][1].ad_unitID];
#else
    [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] AppLovin SDK 不可用，无法加载插屏广告"];
#endif
}

- (void)checkPendingInterstitialDisplay
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 检查待展示的插屏广告"];
    
    if (self.hasShowAd && self.isLoadInterstitial && !self.isUserClosed) {
        [self showInterAd:self.currentScene ?: SCENE_INTER_LEVEL_WIN];
        self.hasShowAd = NO;
    }
}

- (BOOL)isInterstitialReady
{
    BOOL isReady = NO;
#if APPLOVIN_SDK_AVAILABLE
    if (self.isDualAdEnabled) {
        // 双广告位模式下，检查是否有任一广告位就绪
        BOOL primaryReady = self.isPrimaryAdLoaded && self.primaryInterstitialAd && [self.primaryInterstitialAd isReady];
        BOOL secondaryReady = self.isSecondaryAdLoaded && self.secondaryInterstitialAd && [self.secondaryInterstitialAd isReady];
        isReady = primaryReady || secondaryReady;
        
        [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位模式检查插屏广告状态: 主广告位=%@, 备广告位=%@, 总体=%@", 
         primaryReady ? @"就绪" : @"未就绪", secondaryReady ? @"就绪" : @"未就绪", isReady ? @"就绪" : @"未就绪"];
    } else {
        // 单广告位模式
        isReady = (self.interstitialAd && [self.interstitialAd isReady]);
        [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial] 单广告位模式检查插屏广告状态: %@", isReady ? @"就绪" : @"未就绪"];
    }
#endif
    return isReady;
}

- (void)closeInterstitialAd
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 用户主动关闭插屏广告"];
    self.isUserClosed = YES;
}

- (void)resumeInterstitialAd
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 恢复插屏广告展示"];
    self.isUserClosed = NO;
    
    // 根据双广告位模式选择加载方法
    if (self.isDualAdEnabled) {
        [self loadDualInterstitialAds];
    } else {
        [self loadInterstitialAd];
    }
}

#pragma mark - 对外接口方法

- (BOOL)isAdReady {
    if (self.isDualAdEnabled) {
        // 双广告位模式下，检查是否有任一广告位就绪
        BOOL primaryReady = self.isPrimaryAdLoaded && self.primaryInterstitialAd && [self.primaryInterstitialAd isReady];
        BOOL secondaryReady = self.isSecondaryAdLoaded && self.secondaryInterstitialAd && [self.secondaryInterstitialAd isReady];
        BOOL isReady = primaryReady || secondaryReady;
        
        [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位模式检查广告状态: 主广告位=%@, 备广告位=%@, 总体=%@", 
         primaryReady ? @"就绪" : @"未就绪", secondaryReady ? @"就绪" : @"未就绪", isReady ? @"就绪" : @"未就绪"];
        
        return isReady;
    } else {
        // 单广告位模式
        BOOL isReady = (self.interstitialAd && [self.interstitialAd isReady]);
        [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial] 单广告位模式检查广告状态: %@", isReady ? @"就绪" : @"未就绪"];
        return isReady;
    }
}

- (void)setInterTimeSceneEnable:(BOOL)enable {
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 设置时间场景启用状态: %@", enable ? @"启用" : @"禁用"];
    // 这里可以根据需要实现时间场景控制逻辑
    // 目前保持接口兼容性
}

- (void)closeInterstitial {
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 调用关闭插屏广告接口"];
    [self closeInterstitialAd];
}

- (void)resumeInterstitial {
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 调用恢复插屏广告接口"];
    [self resumeInterstitialAd];
}

- (void)loadInterstitial {
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 调用加载插屏广告接口"];
    
    // 根据双广告位模式选择加载方法
    if (self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位模式，加载双广告位"];
        [self loadDualInterstitialAds];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 单广告位模式，加载单广告位"];
        [self loadInterstitialAd];
    }
}

#pragma mark - MAInterstitialAdDelegate
#if APPLOVIN_SDK_AVAILABLE

- (void)didLoadAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] ✅ 插屏广告加载成功"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 广告信息: %@", ad];
    
    // 双广告位模式下的处理
    if (self.isDualAdEnabled) {
        // 判断是主广告位还是备广告位
        if ([ad.adUnitIdentifier isEqualToString:self.currentPrimaryAdUnitId]) {
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 主广告位加载成功"];
            self.isPrimaryAdLoaded = YES;
            self.primaryAdECPM = ad.revenue;
            
            // 埋点：主广告位填充成功
            NSDictionary *fillSuccessParams = @{
                @"w_ad_type": @"interstitial",
                @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
                @"w_network": ad.networkName ?: @"",
                @"w_ad_position": @"primary",
                @"w_ad_revenue": @(ad.revenue)
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
            
        } else if ([ad.adUnitIdentifier isEqualToString:self.currentSecondaryAdUnitId]) {
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 备广告位加载成功"];
            self.isSecondaryAdLoaded = YES;
            self.secondaryAdECPM = ad.revenue;
            
            // 埋点：备广告位填充成功
            NSDictionary *fillSuccessParams = @{
                @"w_ad_type": @"interstitial",
                @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
                @"w_network": ad.networkName ?: @"",
                @"w_ad_position": @"secondary",
                @"w_ad_revenue": @(ad.revenue)
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
        }
        
        // 检查是否有广告位可用
        NSString *selectedAdUnitId = [self selectOptimalAdUnitId];
        if (selectedAdUnitId) {
            self.isLoadInterstitial = YES;
            
            NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didLoadInterstitialForScene:adId:)]) {
                [self.delegate dmAdManager:(DMAdManager *)self didLoadInterstitialForScene:scene adId:selectedAdUnitId];
            }
            
            // 如果有待展示请求，立即展示
            if (self.hasShowAd && !self.isUserClosed) {
                [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 检测到待展示请求，立即展示广告"];
                self.hasShowAd = NO;
                [self showInterAd:self.currentScene ?: SCENE_INTER_LEVEL_WIN];
            }
        }
        
    } else {
        // 单广告位模式
        self.isLoadInterstitial = YES;
        
        // 埋点：填充成功
        NSDictionary *fillSuccessParams = @{
            @"w_ad_type": @"interstitial",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_network": ad.networkName ?: @""
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
        
        NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didLoadInterstitialForScene:adId:)]) {
            [self.delegate dmAdManager:(DMAdManager *)self didLoadInterstitialForScene:scene adId:ad.adUnitIdentifier];
        }
        
        // 如果有待展示请求，立即展示
        if (self.hasShowAd && !self.isUserClosed) {
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 检测到待展示请求，立即展示广告"];
            self.hasShowAd = NO;
            [self showInterAd:self.currentScene ?: SCENE_INTER_LEVEL_WIN];
        }
    }
}

- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error
{
    [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] ❌ 插屏广告加载失败"];
    [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] 错误信息: %@", error.message];
    [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] 错误代码: %ld", (long)error.code];
    
    // 双广告位模式下的处理
    if (self.isDualAdEnabled) {
        // 判断是主广告位还是备广告位失败
        if ([adUnitIdentifier isEqualToString:self.currentPrimaryAdUnitId]) {
            [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] 主广告位加载失败"];
            self.isPrimaryAdLoaded = NO;
            
            // 埋点：主广告位填充失败
            NSDictionary *fillFailParams = @{
                @"w_ad_type": @"interstitial",
                @"w_ad_unit_id": adUnitIdentifier ?: @"",
                @"w_error_code": @(error.code),
                @"w_error_msg": error.message ?: @"加载失败",
                @"w_ad_position": @"primary"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
            
            // 尝试切换到备用广告位
            [self switchToSecondaryAdIfNeeded];
            
        } else if ([adUnitIdentifier isEqualToString:self.currentSecondaryAdUnitId]) {
            [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] 备广告位加载失败"];
            self.isSecondaryAdLoaded = NO;
            
            // 埋点：备广告位填充失败
            NSDictionary *fillFailParams = @{
                @"w_ad_type": @"interstitial",
                @"w_ad_unit_id": adUnitIdentifier ?: @"",
                @"w_error_code": @(error.code),
                @"w_error_msg": error.message ?: @"加载失败",
                @"w_ad_position": @"secondary"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
        }
        
        // 检查是否还有可用的广告位
        NSString *selectedAdUnitId = [self selectOptimalAdUnitId];
        if (!selectedAdUnitId) {
            // 没有可用广告位，设置加载状态为失败
            self.isLoadInterstitial = NO;
            
            // 增加重试计数
            self.retryCount++;
            self.totalFailureCount++;
            
            // 如果未达到最大重试次数，5秒后重新加载双广告位
            if (self.retryCount < self.maxRetryCount && !self.isRetryPaused) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 🔄 5秒后重新加载双广告位 (重试 %ld/%ld)", (long)self.retryCount, (long)self.maxRetryCount];
                    [self loadDualInterstitialAds];
                });
            } else {
                [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] 已达到最大重试次数或重试已暂停"];
            }
        }
        
    } else {
        // 单广告位模式
        self.isLoadInterstitial = NO;
        
        // 埋点：填充失败
        NSDictionary *fillFailParams = @{
            @"w_ad_type": @"interstitial",
            @"w_ad_unit_id": adUnitIdentifier ?: @"",
            @"w_error_code": @(error.code),
            @"w_error_msg": error.message ?: @"加载失败"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
        
        // 5秒后重新加载
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 🔄 5秒后重新加载插屏广告"];
            [self loadInterstitialAd];
        });
    }
}

- (void)didDisplayAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 👁️ 插屏广告开始展示"];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial] AdInfo详情:"];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    
    NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
    [[DMInterstitialSceneInterceptor sharedInterceptor] recordSceneShow:self.currentScene ?: SCENE_INTER_LEVEL_WIN];
    
    // 埋点：展示成功
    NSDictionary *showSuccessParams = @{
        @"w_ad_scene": scene,
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_network": ad.networkName ?: @"",
        @"w_ad_revenue": @(ad.revenue)
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_success" properties:showSuccessParams];
    
    // 埋点：展示完成（插屏广告显示即完成）
    NSDictionary *showCompletedParams = @{
        @"w_ad_scene": scene,
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_network": ad.networkName ?: @"",
        @"w_ad_revenue": @(ad.revenue)
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_completed" properties:showCompletedParams];

    // 新增：AD_Inter_show（带 w_scene 与 w_revenue，单位mUSD）
    @try {
        double ecpm = ad.revenue * 1000.0;
        NSDictionary *interShowParams = @{ @"w_scene": self.currentScene ?: @"interstitial_show", @"w_revenue": @(ecpm),@"w_auctionId":[DMConfigReader auctionId] };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"AD_Inter_show" jsonStr:interShowParams];
        
        ADJAdRevenue *adjustAdRevenue = [[ADJAdRevenue alloc] initWithSource:@"applovin_max_sdk"];
        [adjustAdRevenue setRevenue:ad.revenue currency:@"USD"];
        [adjustAdRevenue setAdRevenueNetwork:ad.networkName];
        [adjustAdRevenue setAdRevenueUnit:ad.adUnitIdentifier];
        [adjustAdRevenue setAdRevenuePlacement:ad.placement];
        [adjustAdRevenue addPartnerParameter:@"ad_format" value:ad.format.label];
        [adjustAdRevenue addPartnerParameter:@"ad_unit_id" value:ad.adUnitIdentifier];
        [Adjust trackAdRevenue:adjustAdRevenue];
        
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 事件上报: AD_Inter_show, w_revenue: %.2f", ecpm];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] 事件上报异常: %@", exception.reason];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowInterstitialForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didShowInterstitialForScene:scene adId:ad.adUnitIdentifier];
    }
}

- (void)didClickAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 👆 插屏广告被点击"];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial] AdInfo详情:"];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [MAX Interstitial]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    
    NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
    
    // 埋点：广告点击
    NSDictionary *clickParams = @{
        @"w_ad_scene": scene,
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_network": ad.networkName ?: @"",
        @"w_ad_revenue": @(ad.revenue)
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_click" properties:clickParams];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didClickInterstitialForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didClickInterstitialForScene:scene adId:ad.adUnitIdentifier];
    }
}

- (void)didHideAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 👻 插屏广告关闭"];
    
    NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didCloseInterstitialForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didCloseInterstitialForScene:scene adId:ad.adUnitIdentifier];
    }
    
    // 重置状态并预加载下一个广告
    self.isLoadInterstitial = NO;
    self.currentScene = nil;
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 🔄 广告关闭，开始预加载下一个插屏广告"];
    
    // 根据双广告位模式选择加载方法
    if (self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位模式，预加载双广告位"];
        [self loadDualInterstitialAds];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 单广告位模式，预加载单广告位"];
        [self loadInterstitialAd];
    }
}

- (void)didFailToDisplayAd:(nonnull MAAd *)ad withError:(nonnull MAError *)error {
    [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] ❌ 插屏广告展示失败"];
    [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] 错误信息: %@", error.message];
    [IMLogUtils error:IMLogTagAd format:@"📱 [MAX Interstitial] 错误代码: %ld", (long)error.code];
    
    NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
    
    // 埋点：展示失败
    NSDictionary *showFailParams = @{
        @"w_ad_scene": scene,
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
        @"w_error_code": @(error.code),
        @"w_error_msg": error.message ?: @"展示失败"
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 埋点事件已发送: showFailed"];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
        NSError *nsError = [NSError errorWithDomain:@"DualMediationMAXInterstitial" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message ?: @"展示失败"}];
        [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:scene error:nsError];
    }
    
    // 重新加载广告
    if (self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 双广告位模式，重新加载双广告位"];
        [self loadDualInterstitialAds];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 单广告位模式，重新加载单广告位"];
        [self loadInterstitialAd];
    }
}
#endif

#pragma mark - MAAdRevenueDelegate

- (void)didPayRevenueForAd:(nonnull MAAd *)ad {
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 💸 ========== 收到 Revenue Data ==========="];
    
    if (!ad || ad.revenue <= 0) {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [MAX Interstitial] ❌ Revenue data 无效或收入为空"];
        return;
    }

    double revenueUSD = ad.revenue;
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 💰 Revenue 收入详情:"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial]   - Revenue: $%.6f", revenueUSD];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial]   - CreativeId: %@", ad.creativeIdentifier ?: @"N/A"];
    
    // 确定广告格式和广告源
    NSString *AdUnitId = ad.adUnitIdentifier ?: @"";
    NSString *ad_format = @"interstitial";
    NSString *adSource = @"unknown";
    
    // 判断是主广告位还是备广告位
    if ([AdUnitId isEqualToString:self.currentPrimaryAdUnitId]) {
        adSource = @"primary";
    } else if ([AdUnitId isEqualToString:self.currentSecondaryAdUnitId]) {
        adSource = @"secondary";
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial]   - ad_format: %@", ad_format];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial]   - ad_source: %@", adSource];
    
    // ========== DMCommercialManager 策略集成 ==========
    DMCommercialManager *commercialSDK = [DMCommercialManager sharedInstance];
    
    // 1. 记录广告位性能数据
    [commercialSDK recordAdUnitPerformance:AdUnitId
                                      ecpm:revenueUSD
                                 fillRate:1.0
                                 clickRate:0.0
                                 isSuccess:YES];
    
    // 2. ECPM比较和广告位优化（双广告位模式）- 仅限插屏广告
    if ([adSource isEqualToString:@"primary"] || [adSource isEqualToString:@"secondary"]) {
        NSString *primaryAdUnitId = [DMConfigReader primaryInterForSDKConfigFileMAX];
        NSString *secondaryAdUnitId = [DMConfigReader secondaryInterForSDKConfigFileMAX];
        
        if (primaryAdUnitId && secondaryAdUnitId) {
            NSString *optimalAdUnitId = [commercialSDK compareAdUnitsAndSelectOptimal:primaryAdUnitId
                                                                    secondaryAdUnitId:secondaryAdUnitId];
            [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 🎯 ECPM比较结果：最优广告位 = %@", optimalAdUnitId];
        }
    }
    
    // ========== 原有上报逻辑保持不变 ==========
    // 1. 上报 Taichi
    NSNumber *revenueMicros = @(revenueUSD * 1000);
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] Taichi 上报完成: %@ micros", revenueMicros];

#if FIREBASE_AVAILABLE
    // 2. Firebase 埋点
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"ad_platform"] = @"MAX";
    params[@"ad_format"] = ad_format;
    params[@"ad_source"] = ad.networkName ?: @"";
    params[@"ad_unit_name"] = ad.adUnitIdentifier ?: @"";
    params[@"ad_unit_source"] = adSource; // 新增：标识主/备用广告位
    params[@"value"] = @(revenueUSD);
    params[@"currency"] = @"USD";
    [FIRAnalytics logEventWithName:@"ad_impression" parameters:params];
    [FIRAnalytics logEventWithName:@"Ad_Impression_Revenue" parameters:params];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] Firebase 埋点完成"];
#endif
    
#if FACEBOOK_AVAILABLE
    // 3. Facebook 事件上报
    NSMutableDictionary *fbParams = [NSMutableDictionary dictionary];
    fbParams[@"ad_platform"] = @"MAX";
    fbParams[@"ad_unit"] = ad.adUnitIdentifier ?: @"";
    fbParams[@"ad_format"] = ad_format;
    fbParams[@"ad_source"] = ad.networkName ?: @"";
    fbParams[@"ad_unit_name"] = ad.adUnitIdentifier ?: @"";
    fbParams[@"ad_unit_source"] = adSource;
    fbParams[@"value"] = @(revenueUSD);
    fbParams[@"currency"] = @"USD";
    [FBSDKAppEvents.shared logEvent:@"ad_impression" parameters:fbParams];
    [FBSDKAppEvents.shared logEvent:@"Ad_Impression_Revenue" parameters:fbParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] Facebook 事件上报完成"];
#endif

    // 4. 10个等级的太极打点机制
    [self reportMultiLevelTaichiRevenue:revenueUSD adFormat:ad_format adSource:adSource];

    [IMLogUtils info:IMLogTagAd format:@"📱 [MAX Interstitial] 💸 Revenue Data 处理完成"];
}

#pragma mark - 10个等级的太极打点机制

// 定义收益等级阈值（插屏广告）
// =============== 配置：10 档（0.01 ~ 0.10，每档 +0.01） ===============
static inline NSArray<NSNumber *> *WDRevenueTiersUSD(void) {
    return @[@0.01, @0.02, @0.03, @0.04, @0.05, @0.06, @0.07, @0.08, @0.09, @0.10];
}

// 事件名与阈值一一对应，001~010 分别对应 0.01~0.10
static inline NSArray<NSString *> *WDRevenueEventNames(void) {
    return @[
        @"Total_Ads_Revenue_001", // 0.01
        @"Total_Ads_Revenue_002", // 0.02
        @"Total_Ads_Revenue_003", // 0.03
        @"Total_Ads_Revenue_004", // 0.04
        @"Total_Ads_Revenue_005", // 0.05
        @"Total_Ads_Revenue_006", // 0.06
        @"Total_Ads_Revenue_007", // 0.07
        @"Total_Ads_Revenue_008", // 0.08
        @"Total_Ads_Revenue_009", // 0.09
        @"Total_Ads_Revenue_010"  // 0.10
    ];
}

// 本地持久化键（插屏广告）
static NSString *const kWDRevenueUSDKey_Interstitial = @"Interstitial_RevenueUSD";
static NSString *const kWDLastTierKey_Interstitial = @"Interstitial_LastTier";

// 串行队列，确保线程安全
static dispatch_queue_t WDRevenueQueue_Interstitial() {
    static dispatch_queue_t queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue = dispatch_queue_create("com.dualmediationsdk.interstitial.revenue", DISPATCH_QUEUE_SERIAL);
    });
    return queue;
}

- (void)reportMultiLevelTaichiRevenue:(double)revenueUSD adFormat:(NSString *)adFormat adSource:(NSString *)adSource {
    dispatch_async(WDRevenueQueue_Interstitial(), ^{
        // 1) 读取当前累计收入
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        double oldTotal = [ud doubleForKey:kWDRevenueUSDKey_Interstitial];
        double newTotal = oldTotal + revenueUSD;
        
        [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier-Interstitial] oldTotal=%.6f | +%.6f | newTotal=%.6f", oldTotal, revenueUSD, newTotal];
        
        // 2) 计算当前档位
        NSArray<NSNumber *> *tiers = WDRevenueTiersUSD();
        NSInteger currentTier = -1;
        for (NSInteger i = 0; i < tiers.count; i++) {
            if (newTotal >= [tiers[i] doubleValue]) {
                currentTier = i;
            } else {
                break;
            }
        }
        
        NSInteger lastTier = -1;
        if ([ud objectForKey:kWDLastTierKey_Interstitial] != nil) {
            lastTier = (NSInteger)[ud integerForKey:kWDLastTierKey_Interstitial];
        }

        [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier-Interstitial] lastTier=%ld | currentTier=%ld", (long)lastTier, (long)currentTier];

        // 3) 补齐新跨越的档位
        if (currentTier > lastTier) {
            NSArray<NSString *> *eventNames = WDRevenueEventNames();
            for (NSInteger i = lastTier + 1; i <= currentTier; i++) {
                NSString *eventName = eventNames[i];
                NSNumber *threshold = tiers[i];

                // Firebase：事件名与门槛一一对应
                NSDictionary *fa = @{
                    kFIRParameterValue: @(newTotal),         // 传累计总额（便于分析）
                    @"threshold": threshold,                // 当前门槛
                    @"ad_format": adFormat,                 // 广告格式
                    @"ad_source": adSource                  // 广告源
                };
#if FIREBASE_AVAILABLE
                [FIRAnalytics logEventWithName:eventName parameters:fa];
#endif
                
                // Facebook：同样的事件名和参数
                NSDictionary *fb = @{
                    @"value": @(newTotal),
                    @"threshold": threshold,
                    @"ad_format": adFormat,
                    @"ad_source": adSource
                };
#if FACEBOOK_AVAILABLE
                [FBSDKAppEvents.shared logEvent:eventName parameters:fb];
#endif
                
                [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier-Interstitial] 🎯 触发里程碑: %@ (门槛=%.2f, 累计=%.6f)", eventName, [threshold doubleValue], newTotal];
            }
        }
        
        // 4) 更新本地存储
        [ud setDouble:newTotal forKey:kWDRevenueUSDKey_Interstitial];
        if (currentTier >= 0) {
            [ud setInteger:currentTier forKey:kWDLastTierKey_Interstitial];
        }
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"Interstitial_RevenueUSD"];
    });
}

// 调试辅助方法：重置收益里程碑（插屏广告）
- (void)wd_resetRevenueMilestonesForDebug_Interstitial {
    dispatch_async(WDRevenueQueue_Interstitial(), ^{
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud removeObjectForKey:kWDRevenueUSDKey_Interstitial];
        [ud removeObjectForKey:kWDLastTierKey_Interstitial];
        [ud synchronize];
        [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier-Interstitial] 🔄 收益里程碑已重置"];
    });
}

@end
